/**
 * Created by Administrator on 2015/12/1.
 */
var express = require('express');
var app = express();
var logger = require('morgan');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var path = require('path');
var dg = require('./service/dg');
var session = require('express-session');
/**
 * router module
 */
var user = require('./router/user.js');
var article = require('./router/article.js');
var comment = require('./router/comment.js');
/**
 * router end
 */
//app.set('views',path.join(__dirname,'views'));
//app.set('view engine','ejs');
//app.engine('.html',require('ejs').__express);
//app.set('view engine','html');

//app.set("view engine", "ejs");
//app.set("views", __dirname + "/views");
//app.set("view options", { layout: false } );
//使用engine方法定义了一个模板引擎
//第一个参数是模板扩展名，第二个参数是处理方法
//这里使用的EJS方法来处理
app.engine('.html',dg.__express)

app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');
//此处使用上面定义的模板
app.set('view engine','html');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(cookieParser());
//app.use(session(
//    {
//    genid:function(req){
//            return genuuid();
//        },
//    secret: 'keyboard cat',
//    resave:true,
//    saveUninitialized:true,})
//);
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false ,maxAge:300000}
}))
app.use(express.static('pub'));

app.use(function(req,res,next){
    if(req.session){
        var session = req.session;
        if(session.count){
            session.count = session.count + 1;
        }else{
            session.count = 1;
        }
        console.log(session.count);
    }
    next();
});

app.get('/',function(req,res){
    //console.log('root is called!');
    console.log(req.session);
    console.log(req.sessionID);
    res.render('index-2',{sessionID:req.sessionID,session:req.session});
    //res.render('index',{sessionID:req.sessionID,count:req.session.count});
});

app.get('/test',function(req,res){
    res.render('test',{sessionID:req.sessionID});
});

app.use('/user',user);
app.use('/article',article);
app.use('/comment',comment);
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.use(function(err, req, res, next) {
    res.status(err.status || 500);
//    res.render('error', {
//        message: err.message,
//        error: {}
//    });
    res.redirect('/404.html');
});

var server = app.listen(3000,function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listen at http://%s:%s',host,port);
});